package com.primestone.cim.async;


import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.xml.bind.JAXBException;

import com.primestone.cim.meterreadings.beans.QueueMessage;
import com.primestone.cim.util.StringUtil;
import com.primestone.cim.util.XMLUtil;

/**
 * 
 * @author cesar.mateus
 *
 */
@Stateless( name = StringUtil.QUEUEUPGETMR_NAME )
@TransactionManagement( TransactionManagementType.BEAN )
public class QueueUpBean implements QueueUpLocal {
	
	private final static Logger LOGGER = Logger.getLogger(QueueUpBean.class.getName());
    
    @Resource(mappedName = StringUtil.CONN_FACTORY_JNDI_NAME)
    private ConnectionFactory connectionFactory;

    @Resource(mappedName = StringUtil.DESTINATION_GET_MR_QUEUE)
    private Queue queue;

    /**
     * 
     */
    public QueueUpBean() {}
    
    /**
     *
     * @param message
     * @throws QueueException
     */
    @Override
    public void receiveQueueMessage( Serializable message ) throws Exception {        
        try {
        	LOGGER.log(Level.FINE, "---- En el ejb que coloca el request");
            if (message instanceof QueueMessage) {
            	putRequest((QueueMessage)message);
            } else {
            	LOGGER.log(Level.WARNING, "---- Ignoring message.");
            }
            
            LOGGER.log(Level.FINE, "---- El ejb ha colocado el request");
        } catch( JMSException e ) {
        	LOGGER.log(Level.WARNING, "---- JMS Exception enqueueing: {0}", e.getMessage());
            //e.printStackTrace();
            throw new Exception( e );
        } catch (Throwable e) {
        	LOGGER.log(Level.WARNING, "---- Fundamental Exception enqueueing: {0}", e.getMessage());
            //e.printStackTrace();
            throw new Exception( e );
        }
    }
    
    /**
     *
     * @param message
     * @throws JMSException
     * @throws JAXBException 
     */
    private void putRequest( QueueMessage message ) throws JMSException, JAXBException {
        Connection conn = null;
        Session session = null;
        MessageProducer producer = null;
        try {
            conn = this.connectionFactory.createConnection();
            session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(this.queue);
            
            BytesMessage bytesMessage = session.createBytesMessage();
            bytesMessage.writeBytes(XMLUtil.marshall(message));
            
            bytesMessage.setStringProperty("user", message.getHeader().value.getUser().getUserID());
             
            producer.send(bytesMessage);
            LOGGER.log(Level.INFO, "---- Message enqueued.");
        } finally {
            if( session != null ) {
                session.close();
            }
            if( conn != null ) {
                conn.close();
            }
        }
    }
    
}
